package com.xq.tmall.service;


import com.xq.tmall.dao.StockHistoryDao;
import com.xq.tmall.entity.Stock;
import com.xq.tmall.entity.StockHistory;
import com.xq.tmall.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class StockHistoryService {

    @Resource
    private StockHistoryDao stockHistoryDao;

    public void batchInsert(List<Stock> stockList) throws Exception {
        List<StockHistory> stockHistoryList = new ArrayList<>();
        stockList.stream().forEach(stock -> {
            StockHistory stockHistory = new StockHistory();
            try {
                BeanUtils.copyProperties(stock,stockHistory);
            }catch (Exception e){
                log.info("转换失败",e );
            }
            stockHistory.setPriceDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
            stockHistoryList.add(stockHistory);
        });
        List<List<StockHistory>> listList = BeanUtil.splitsList(stockHistoryList, 500);
        for (List<StockHistory> list : listList) {
            stockHistoryDao.batchInsert(list);
        }
    }

    public void historyDelete(String historyDate) {
        stockHistoryDao.historyDelete(historyDate);
    }
    public void nowDelete(String historyDate) {
        stockHistoryDao.nowDelete(historyDate);
    }

    public List<StockHistory> findStockHistoryList(Map<String,Object> params) {
        List<StockHistory> stockHistoryList = stockHistoryDao.findStockHistoryList(params);
        return stockHistoryList;
    }

    public void batchInsertBid(List<Stock> stockList) throws Exception {
        List<StockHistory> stockHistoryList = new ArrayList<>();
        stockList.stream().forEach(stock -> {
            StockHistory stockHistory = new StockHistory();
            try {
                stockHistory.setCode(stock.getCode());
                stockHistory.setName(stock.getName());
                stockHistory.setPrice(stock.getPrice());
                stockHistory.setTotalValue(stock.getPrice());
                stockHistory.setYesterdayPrice(stock.getYesterdayPrice());
                stockHistory.setGoPettm(stock.getGoPettm());
                stockHistory.setBiddingVolume(stock.getBiddingVolume());
                stockHistory.setBidPrice(stock.getBidPrice());
            }catch (Exception e){
                log.info("转换失败",e );
            }
            stockHistory.setPriceDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
            stockHistoryList.add(stockHistory);
        });
        List<List<StockHistory>> listList = BeanUtil.splitsList(stockHistoryList, 500);
        for (List<StockHistory> list : listList) {
            stockHistoryDao.batchInsert(list);
        }
    }
}
